package org.zjx.command;

import lombok.Data;
import org.zjx.core.GameWindow;
import org.zjx.exception.ActivationException;
import org.zjx.manager.ActivationManager;

@Data
public abstract class Command implements ICommand{
    protected final GameWindow targetWindow; // 目标窗口
    private final boolean requiresActivation; // 是否需要激活
    private final String commandName; // 指令名称（用于日志）

    /**
     * 构造函数
     * @param targetWindow 目标窗口
     * @param requiresActivation 是否需要激活
     * @param commandName 指令名称
     */
    public Command(GameWindow targetWindow, boolean requiresActivation, String commandName) {
        if (targetWindow == null) {
            throw new IllegalArgumentException("Target window cannot be null");
        }
        this.targetWindow = targetWindow;
        this.requiresActivation = requiresActivation;
        this.commandName = commandName != null ? commandName : this.getClass().getSimpleName();
    }

    /**
     * 执行指令的主入口方法
     * 处理激活权的申请和释放
     */
    @Override
    public final void execute() {
        boolean activationAcquired = false;

        try {
            // 如果需要激活，申请激活权
            if (requiresActivation) {
                activationAcquired = ActivationManager.requestActivation(targetWindow);
                if (!activationAcquired) {
                    throw new ActivationException("Failed to acquire activation for command: " + commandName);
                }
            }

            // 执行具体的指令逻辑
            doExecute();

        } finally {
            // 如果获得了激活权，必须释放
            if (activationAcquired) {
                ActivationManager.releaseActivation(targetWindow);
            }
        }
    }

    /**
     * 抽象方法 - 子类实现具体的指令逻辑
     */
    protected abstract void doExecute();

}
